package com.dragon.modules.yuegou.client.wechat_mini.model;

import com.dragon.modules.yuegou.web.Check;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;

import java.time.Duration;
import java.time.LocalDateTime;

/**
 * 微信接口调用凭证
 * 
 * @author liuwu
 *
 */
public class AccessToken implements java.io.Serializable {

	private static final long serialVersionUID = 1L;

	public static final int DEFAULT_EXPIRES = 7200;

	/**
	 * access_token值
	 */
	private final String value;

	/**
	 * 创建时间
	 */
	private final LocalDateTime createTime;

	/**
	 * 超时时间
	 */
	private final LocalDateTime expiresTime;

	public AccessToken(String value) {
		this(value, DEFAULT_EXPIRES, LocalDateTime.now());
	}

	public AccessToken(String value, int expires) {
		this(value, expires, LocalDateTime.now());
	}

	public AccessToken(String value, int expires, LocalDateTime createTime) {
		this(value, createTime, createTime.plusSeconds(expires));
	}

	@JsonCreator
	public AccessToken(@JsonProperty("value") String value, @JsonProperty("createTime") LocalDateTime createTime,
			@JsonProperty("expiresTime") LocalDateTime expiresTime) {
		super();
		Check.notEmpty(value, "value is required");
		Check.notNull(createTime, "createTime is required");
		Check.notNull(expiresTime, "expiresTime is required");
		this.value = value;
		this.createTime = createTime;
		this.expiresTime = expiresTime;
	}

	/**
	 * 获取access_token值
	 * 
	 * @return access_token值
	 */
	public String getValue() {
		return value;
	}

	/**
	 * 获取access_token创建时间
	 * 
	 * @return 创建时间
	 */
	public LocalDateTime getCreateTime() {
		return createTime;
	}

	/**
	 * 获取access_token失效时间
	 * @return access_token失效时间
	 */
	public LocalDateTime getExpiresTime() {
		return expiresTime;
	}

	public boolean isExpiredAt(LocalDateTime time) {
		return expiresTime.isBefore(time);
	}

	/**
	 * 判断过一段时间后accessToken是否失效
	 * 
	 * @param duration 时间间隔
	 * @return true表示accessToken过一段时间后会失效，false表示accessToken过一段时间后也不会失效
	 */
	public boolean isExpiresAfter(Duration duration) {
		return this.isExpiredAt(LocalDateTime.now().plus(duration));
	}

	@JsonIgnore
	public boolean isExpired() {
		return this.isExpiredAt(LocalDateTime.now());
	}

	@Override
	public String toString() {
		return String.format("AccessToken [value=%s, createTime=%s, expiresTime=%s]", value, createTime, expiresTime);
	}
}
